package com.hangzhou.xyj.net.http.base;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.net.handler.base.BaseHttpHandler;
import com.hangzhou.xyj.net.okhttp.helper.ProgressHelper;
import com.hangzhou.xyj.net.okhttp.listener.impl.UIProgressListener;
import com.hangzhou.xyj.net.response.base.BaseResponse;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.constants.API;

import org.apache.http.protocol.HTTP;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

/**
 * 公共请求基类
 *
 * @author neo.duan
 */
public class BaseHttpLoader {
    private static final OkHttpClient client = new OkHttpClient.Builder()
            //设置超时，不设置可能会报异常
            .connectTimeout(1000, TimeUnit.MINUTES)
            .readTimeout(1000, TimeUnit.MINUTES)
            .writeTimeout(1000, TimeUnit.MINUTES)
            .build();
    protected final String TAG = getClass().getSimpleName();
    private RequestQueue mReqQueue;
    private Context mContext;

    protected BaseHttpLoader() {
        this.mContext = XYJApplication.getInstance();
    }

    public RequestQueue getReqQueue() {
        return mReqQueue;
    }

    protected void setPostRequest(final BaseHttpHandler handler) {
        Log.d(TAG, "request url---> " + handler.getRequest().getUrl());

        final Map<String, String> map = new HashMap<String, String>();//需要传递参数的map
        for (Map.Entry<String, Object> entry : handler.getRequest().getParams().entrySet()) {
            Log.d(TAG, "req params--->" + "key=" + entry.getKey() + ",value=" + entry.getValue());
            map.put(entry.getKey(), entry.getValue().toString());//添加需要传递的参数到Map中
        }
        mReqQueue = Volley.newRequestQueue(mContext);
        mReqQueue.cancelAll(handler.getRequest().getUrl());
        Request<JsonObject> request = new Request<JsonObject>(Method.POST, handler.getRequest().getUrl(), handler) {

            //服务器返回
            @Override
            protected void deliverResponse(JsonObject object) {
                handler.onResponse(object);
            }

            //服务器返回
            @Override
            protected Response<JsonObject> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    /**
                     * 得到返回的数据用UTF_8编码
                     */
                    String jsonStr = new String(response.data,HTTP.UTF_8);
                    Log.d("debug", jsonStr);
                    /**
                     * 转化成对象
                     */
                    return Response.success(new JsonParser().parse(jsonStr).getAsJsonObject(), HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (JsonSyntaxException e) {
                    return Response.error(new ParseError(e));
                }
            }

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                if (StringUtil.isNotEmpty(XYJApplication.mToken)) {
                    map.put("token", XYJApplication.mToken);
                }
                return map;
            }

            @Override
            public byte[] getBody() throws AuthFailureError {
                return super.getBody();
            }
        };

        mReqQueue.add(request);
    }


    /**
     * 上传单个文件
     *
     * @param filePath 文件路径
     */
    public void uploadFile(String filePath, final UIProgressListener uiProgressRequestListener) {
        File file = new File(filePath);
        //构造上传请求，类似web表单
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), RequestBody.create(null, file))
                .build();

        //进行包装，使其支持进度回调
        final okhttp3.Request request = new okhttp3.Request.Builder().url(API.FILE_UPLOAD).post(ProgressHelper
                .addProgressRequestListener(requestBody, uiProgressRequestListener)).build();
        //开始请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure:" + e.getMessage());
                uiProgressRequestListener.onUIFail(e.getMessage());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                uiProgressRequestListener.onUIFinish(new Gson().fromJson(response.body().string(), BaseResponse.class));
            }

        });

    }

    /**
     * 更新头像
     *
     * @param filePath 文件路径
     * @param imageIs  图片的字节流
     * @api filePath 上传api
     */
    public void uploadHeadImg(String filePath, String userId, String url, byte[] imageIs, final UIProgressListener uiProgressRequestListener) {
        File file = new File(filePath);
        //构造上传请求，类似web表单
        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("headImg", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), imageIs))
                .addFormDataPart("userId", userId)
                .build();

        //进行包装，使其支持进度回调
        final okhttp3.Request request = new okhttp3.Request.Builder().url(url).post(ProgressHelper
                .addProgressRequestListener(requestBody, uiProgressRequestListener)).build();
        //开始请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure:" + e.getMessage());
                uiProgressRequestListener.onUIFail(e.getMessage());
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                uiProgressRequestListener.onUIFinish(new Gson().fromJson(response.body().string(), BaseResponse.class));
            }

        });

    }

}
